package com.szz.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 返回页面处理器
 */
@Configuration
public class RestAuthorizationAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
        // 设置数据类型
        response.setContentType("application/json;charset=utf-8");
        // 封装数据
        Map<String, Object> data = new HashMap<>(4);
        data.put("code", "403");
        data.put("msg", "您没有访问权限");
        // 拿到响应流
        PrintWriter writer = response.getWriter();
        // 创建类型转换器
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(data);
        // 将数据写出去
        writer.write(s);
        writer.flush();
        writer.close();
    }
}
